window.onload = function () {
    const embed = getUrlParam('embed');
    if(!embed){
        initApp();
    }
};

// ------- 以嵌入的方式加载 --------
window.addEventListener("message",function (e){
    console.log(e.origin);
    console.log(e.data);
    if(e.data.apiKey !== '123456789'){
        e.source.postMessage({code:-1,msg:'apiKey error'}, e.origin);
        return;
    }
    window.callerProxy.origin = e.origin;
    window.callerProxy.caller = e.source;
    if(!e.data.cmd){
        return;
    }
    switch (e.data.cmd) {
        case 'init': Cookies.set('userAuid', e.data.extras.userAuid);Cookies.set('userToken', e.data.extras.userToken);initApp();sendResizeMessage('minimum');break;
    }

    e.source.postMessage({cmd: 'ack', code:0,msg:'ok'}, e.origin);
},true);

function sendResizeMessage(size){
    window.callerProxy.post({
        cmd: 'resize',
        extras:{
            size: size // 'full', 'minimum'
        }
    })
}
function sendHideAppMessage(){
    window.callerProxy.post({
        cmd: 'hide'
    })
}



window.callerProxy = {
     origin:null,
     caller:null,
     post:function (msg) {
         if(!this.origin || !this.caller){
             return;
         }
         this.caller.postMessage(msg, this.origin);
     }
};



function initApp() {
    const app = window.app = new Vue({
        el: "#app",
        data: {
            // windows 窗口 (chat:聊天, system:系统消息)
            windowTab: '',
            online: 0,
            avatarType: '', // 修改头像的类型 (self:自己的头像; room: 讨论组的头像)
            sessionTopList: ['添加好友','添加讨论组', '系统消息'], // 放置在会话列表的功能列表
            sessionList: [], // 会话列表
            friendList: [], // 好友列表
            roomList: [], // 讨论组列表
            friendToAddRoomList: [], // 待添加到讨论组的朋友列表
            listExtraInfo: {}, // 会话列表, 好友列表, 讨论组列表 的补充信息
            // 好友聊天消息
            // friendMessages: [],
            faces: faces, // 表情gif
            // 系统消息
            systemMessages: [{text: 'XXX加你好友了', createTime: '2019-12-02 11:22'}],
            // 用户信息
            userInfo: {
                auid: '',// 用户auid
                birth: '',  // 生日 (YYYY-MM-dd)
                mobile: '',  // 用户mobile
                email: '',  // 用户email
                sign: '',  // 用户签名
            },
            // 聊天正文
            chatsContent: {
                // 好友信息
                friendInfo: {
                    alias: '', // 备注名
                    auid: '', // 账号
                    name: '', // 名字
                    avatar: '', // 头像
                    online: 0, // 是否在线(0:离线; 1:在线)
                    memo: '', // 备注
                    birth: '2020-01-01',  // 生日 (YYYY-MM-dd)
                    mobile: '13800138000',  // 用户mobile
                    email: '',  // 用户email
                    sign: '',  // 用户签名,
                    blacklist: false,
                    forbid: true,
                },
                // 群信息
                roomInfo: {
                    rid: 0,   // 群ID
                    name: '', // 名字
                    avatar: '', // 头像
                    // online: 0, // 是否在线(0:离线; 1:在线)
                    memo: '', // 备注
                    birth: '2020-01-01',  // 生日 (YYYY-MM-dd)
                    mobile: '13800138000',  // 用户mobile
                    email: '',  // 用户email
                    sign: '',  // 用户签名,
                    blacklist: false,
                    forbid: true,
                },
                select: 'friend', // 聊天对象(friend: 好友; room: 群)
                selectId: '', // 聊天对象ID(用户auid; 群ID)
                chats: [] // 聊天记录
            },
            // 发送的内容
            msgContent: {
                text: ''
            },
            // 要添加的好友
            friendAdd: {
                auid: ''
            },

        },
        filters:{
            faceMessage: function(message){
                return facesUtils.convertToResource(message.body);
            }
        },
        updated: function () {
            // console.log("updated");
        },
        mounted: function () {
            // console.log("mounted");
            document.getElementById('app').style.display = "inline";
        },
        methods: {
            showToast(msg) {
                this.toastCount++;
                this.$bvToast.toast(`${msg}`, {
                    title: '提示',
                    autoHideDelay: 2000,
                    appendToast: false
                })
            },
            showApiErrorToast(e) {
                // 捕捉API错误返回结果
                if(typeof e === "object" && e.hasOwnProperty('responseCode') && e.responseCode === 200){
                    if(e.errorCode === -203){
                        this.showToast('用户登录失败.');
                        Cookies.set('userAuid', null);
                        Cookies.set('userToken', null);
                        setTimeout(function() {
                            window.location.href = "/"; // 登录错误时返回到登录页
                        }, 3000);
                        return;
                    }
                }
                console.error(e);
                if (e instanceof Error) {
                    this.showToast(e);
                } else if (e.errorMessage !== undefined) {
                    this.showToast(e.errorMessage);
                }
            },
            // 重新从后端加载数据
            reloadData(){
                window.location.reload(true);
            },
            showModifyAvatarModal(avatarType) {
                app.avatarType = avatarType;
                app.$bvModal.show('modify-avatar-modal');
            },
            afterShowAvatar(){
                // 绑定上传头像组件
                fileUtils.bindAvatar('uploadAvatar', function (fileInfo) {
                    if(app.avatarType === 'self'){
                        app.userInfo.avatar = fileInfo.url;
                    }
                    else if(app.avatarType === 'room'){
                        app.chatsContent.roomInfo.avatar = fileInfo.url;
                    }
                });
            },
            modifyAvatar() {
                // 修改我的头像
                if(app.avatarType === 'self'){
                    im.apis.userUpdate.call(app.userInfo).then((resp) => {
                        app.showToast("修改成功");
                    }).catch((e) => {
                        app.showApiErrorToast(e);
                    })
                }
                // 修改讨论组头像
                else if(app.avatarType === 'room'){
                    im.apis.updateRoom.call(this.chatsContent.roomInfo).then((resp) => {
                        app.showToast("修改成功")
                    }).catch((e) => {
                        app.showApiErrorToast(e);
                    })
                }
            },
            uploadAvatar() {
                if(app.avatarType === 'self'){
                    app.userInfo.avatar = 'http://img.qqzhi.com/uploads/2019-02-28/093705521.jpg';// TODO: 上传到文件服务器后获取
                }
                else if(app.avatarType === 'room'){
                    app.chatsContent.roomInfo.avatar = 'http://img.qqzhi.com/uploads/2019-02-28/093705521.jpg';// TODO: 上传到文件服务器后获取
                }
            },

            showModifyUserInfoModal() {
                // this.$refs['modify-userinfo-modal'].show();
                // 从后台获取实时的用户信息
                im.apis.userGet.call({auid: app.userInfo.auid}).then((resp) => {
                    app.userInfo = resp.data;
                    app.$bvModal.show('modify-userinfo-modal');
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            modifyUserInfo() {
                im.apis.userUpdate.call(app.userInfo).then((resp) => {
                    app.showToast("修改成功")
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            showModifyFriendAliasModal() {
                // 从后台获取实时的用户信息
                im.apis.getFriend.call({auid:app.userInfo.auid, targetAuid: app.chatsContent.friendInfo.auid}).then((resp) => {
                    app.chatsContent.friendInfo = Beans.replace(app.chatsContent.friendInfo, resp.data);
                    app.chatsContent.friendInfo.blacklist = app.chatsContent.friendInfo.blacklist === 1;
                    app.chatsContent.friendInfo.forbid = app.chatsContent.friendInfo.forbid === 1;
                    app.$bvModal.show('modify-friendinfo-modal');
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },

            modifyFriendAlias() {
                im.apis.modifyAlias.call(
                    {
                        auid:app.userInfo.auid,
                        targetAuid: app.chatsContent.friendInfo.auid,
                        alias:app.chatsContent.friendInfo.alias
                    }).then((resp) => {
                    app.showToast("修改成功")
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            modifyFriendBlackList() {
                var prevStatus = app.chatsContent.friendInfo.blacklist;
                var toChange = prevStatus ? 'REMOVE_BLACKLIST' : 'ADD_BLACKLIST';
                im.apis.modifyBlacklistForbid.call(
                    {
                        auid:app.userInfo.auid,
                        targetAuid: app.chatsContent.friendInfo.auid,
                        type:toChange
                    }).then((resp) => {
                    app.showToast("修改成功");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            modifyFriendForbid() {
                var prevStatus = app.chatsContent.friendInfo.forbid;
                var toChange = prevStatus ? 'REMOVE_FORBID' : 'ADD_FORBID';
                im.apis.modifyBlacklistForbid.call(
                    {
                        auid:app.userInfo.auid,
                        targetAuid: app.chatsContent.friendInfo.auid,
                        type:toChange
                    }).then((resp) => {
                    app.showToast("修改成功");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            delFriend(){
                im.apis.delFriend.call(
                    {
                        auid:app.userInfo.auid,
                        targetAuid: app.chatsContent.friendInfo.auid,
                    }).then((resp) => {
                    app.showToast("操作成功");
                    app.reloadData("friend");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            showModifyRoomInfoModal(){
                // 从后台获取实时的讨论组信息
                im.apis.getRoom.call({rid:app.chatsContent.roomInfo.rid}).then((resp) => {
                    app.chatsContent.roomInfo = Beans.replace(app.chatsContent.roomInfo, resp.data);
                    app.$bvModal.show('modify-roominfo-modal');
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            modifyRoomInfo() {
                console.log('modifyRoomInfo:' + Beans.json(this.chatsContent.roomInfo));
                im.apis.updateRoom.call(this.chatsContent.roomInfo).then((resp) => {
                    app.showToast("修改成功")
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },

            // 添加用户到讨论组里
            addRoomModal() {
                this.friendToAddRoomList = this.friendList.map(function (v) {
                    v.selected = '0'; // 默认值('1': 选中, '0': 未选中)
                    return v;
                });
                this.$bvModal.show('add-room-modal');
            },
            // 追加用户到讨论组里
            appendRoomUserModal(rid) {
                im.apis.listRoomMember.call({rids:[rid]}).then((resp) => {
                    var membersMapByAuid = {};
                    if(resp.data && resp.data.length > 0){
                        for(var v in resp.data[0].members){
                            membersMapByAuid[resp.data[0].members[v].auid] = resp.data[0].members[v];
                        }
                    }
                    // 排除已在群内的成员
                    app.friendToAddRoomList = this.friendList.filter(function (v) {
                        return Object.keys(membersMapByAuid).indexOf(v.auid) === -1;
                    });
                    app.$bvModal.show('add-room-modal');
                }).catch((e) => {
                    app.showApiErrorToast(e);
                });
            },

            selectUserToRoom(auid){
                var userSelected = this.friendToAddRoomList.filter(function (v) {
                    return v.auid === auid;
                });
                if(userSelected.length > 0){
                    userSelected[0].selected = userSelected[0].selected === "1" ? "0" : "1";
                }
                // 需要手动刷新
                this.$forceUpdate();
                return false;
            },
            // 添加群
            addRoom() {
                var friendToAddRoomList = this.friendToAddRoomList.filter(function (v) {
                    return v.selected === '1';
                });
                if(friendToAddRoomList.length === 0){
                    app.showToast("请选择群成员.");
                    return;
                }
                var membersAuid = friendToAddRoomList.map(function(v){
                    return v.auid;
                });
                var membersName = friendToAddRoomList.map(function(v){
                    return v.name;
                });
                im.apis.addRoom.call(
                    {
                        name:'讨论组(' + membersName.join() + ")",
                        owner:app.userInfo.auid,
                        members:membersAuid
                    }).then((resp) => {
                    app.showToast("操作成功");
                    app.reloadData("room");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },

            addFriendModal() {
                console.log("addFriend:" + this.friendAdd.auid);
                this.$bvModal.show('add-friend-modal');
            },
            addFriend() {
                console.log("addFriend:" + this.friendAdd.auid);
                const form = {
                    auid: this.userInfo.auid,
                    targetAuid: this.friendAdd.auid,
                    type: 'ADD',
                    alias: '',
                    applyText: '我要加你好友了'
                };
                im.apis.addFriend.call(form).then((resp) => {
                    app.showToast("添加好友成功.");
                    app.$bvModal.hide('add-friend-modal');
                    // 刷新好友列表
                    im.apis.listFriends.call({auid: app.userInfo.auid}).then((resp) => {
                        app.friendList = resp.data;
                    }).catch((e) => {
                        console.error(e);
                    })
                }).catch((e) => {
                    app.showApiErrorToast(e);
                });
            },
            selectWindowTab(tab, target, fromList) {
                this.windowTab = tab;
                // 从 最近会话/朋友列表/群列表 中点进来
                if (tab === 'chat') {
                    if (fromList === 'session') {
                        this.chatsContent.select = 'session';
                        this.chatsContent.selectId = target.toTarget;
                        this.chatsContent.friendInfo.auid = target.toTarget;
                        this.chatsContent.friendInfo.name = target.toTargetName;
                        this.chatsContent.friendInfo.avatar = target.toTargetAvatar;
                    } else if (fromList === 'friend') {
                        this.chatsContent.select = 'friend';
                        this.chatsContent.selectId = target.auid;
                        this.chatsContent.friendInfo.auid = target.auid;
                        this.chatsContent.friendInfo.name = target.name;
                        this.chatsContent.friendInfo.avatar = target.avatar;
                    } else if (fromList === 'room') {
                        this.chatsContent.select = 'room';
                        this.chatsContent.selectId = target.rid;
                        this.chatsContent.roomInfo.rid = target.rid;
                        this.chatsContent.roomInfo.owner = target.owner;
                        this.chatsContent.roomInfo.name = target.name;
                        this.chatsContent.roomInfo.avatar = target.avatar;
                        // this.chatsContent.chats = [];
                    } else {
                        return;
                    }
                    sendResizeMessage('full');
                    this.cleanUnReadMessage(this.chatsContent.selectId); // 清空消息未读数
                    console.log("chat to user:" + this.chatsContent.friendInfo.auid);
                    this.chatsContent.friendInfo.online = target.online; // TODO: get online status
                    // 获取自己跟 好友/群 的聊天记录
                    const historyListForm = {
                        fromUser: this.userInfo.auid,
                        toTarget: this.isSelectPersonTag() ? this.chatsContent.friendInfo.auid : this.chatsContent.roomInfo.rid,
                        way: this.isSelectPersonTag() ? 'P2P' : 'P2R',
                        startTimestamp: 0,
                        endTimestamp: new Date().getTime(),
                        limit: 20
                    };
                    im.apis.historyListMessage.call(historyListForm).then((resp) => {
                        const msgs = resp.data.reverse();
                        app.chatsContent.chats = msgs;
                        app.scrollMessageContainerToBottom();
                    }).catch((e) => {
                        app.showApiErrorToast(e);
                        app.scrollMessageContainerToBottom();
                    })
                }

                setTimeout(function () {
                    // 绑定发图片/发文件的控件
                    fileUtils.bindImage('sendImageMessage', function (fileInfo) {
                        const way = (app.chatsContent.select==='friend' || app.chatsContent.select==='session') ? 'P2P' : 'P2R';
                        app.sendMessage(way, 'IMAGE', {
                            body:fileInfo.url,
                            name:fileInfo.originFileName,
                            size:fileInfo.size
                        });
                    });
                    // 绑定发文件的控件
                    fileUtils.bindFile('sendFileMessage', function (fileInfo) {
                        console.log(`fileInfo:` + Beans.json(fileInfo));
                    }, function (fileInfo) {
                        const way = (app.chatsContent.select==='friend' || app.chatsContent.select==='session') ? 'P2P' : 'P2R';
                        app.sendMessage(way, 'FILE', {
                            body:fileInfo.url,
                            name:fileInfo.originFileName,
                            size:fileInfo.size
                        });
                    });
                },100)
            },
            closeChatWindows() {
               this.windowTab = '';
                sendResizeMessage('minimum');
            },
            hideChatApp(){
                sendHideAppMessage();
            },
            userLogout() {
                console.log("userLogout");
                if (window.im) {
                    window.im.getSocket().disConnect();
                }
                window.location.href = "/";
            },

            sendMessage(way, type, jsonBody) {
                if (way === 'P2P' || way === 'P2R') {
                    const form = {
                        fromUser: this.userInfo.auid,
                        toTarget: way === 'P2P' ? this.chatsContent.friendInfo.auid : this.chatsContent.roomInfo.rid,
                        way: way,
                        type: type, // 消息类型:TEXT,IMAGE,FILE
                        body: jsonBody
                    };
                    im.apis.sendMessage.call(form).then((resp) => {
                        if (app.windowTab === 'chat') {
                            // 加入刚刚发的信息到聊天窗口
                            app.chatsContent.chats.push({
                                toMe: 0,
                                type:type,
                                way:way,
                                body: jsonBody,
                                createTime: new Date().toLocaleString()
                            });
                            // 清空聊天发送框
                            app.msgContent.text = '';
                        }
                        app.showToast("发送成功");
                        app.scrollMessageContainerToBottom();
                    }).catch((e) => {
                        app.showApiErrorToast(e);
                    })
                }
            },
            showFullImage(url){
                window.open(url);
            },
            appendFace(faceName){
                app.msgContent.text += faceName;
            },
            sendImage(){
                var way = (app.chatsContent.select=='friend' || app.chatsContent.select=='session') ? 'P2P' : 'P2R';
                app.sendMessage(way, 'IMAGE', 'http://img.qqzhi.com/uploads/2019-02-28/093705521.jpg');
                app.$bvModal.hide('select-file-modal');
            },
            sendFile(){
                var way = (app.chatsContent.select=='friend' || app.chatsContent.select=='session') ? 'P2P' : 'P2R';
                app.sendMessage(way, 'FILE', 'http://img.qqzhi.com/uploads/2019-02-28/093705521.jpg');
                app.$bvModal.hide('select-file-modal');
            },
            // 让聊天框滚动到底部
            scrollMessageContainerToBottom() {
                this.$nextTick(function () {
                    var chatContainer = document.getElementById('chat-body-container');
                    if (chatContainer) {
                        chatContainer.scrollTop = chatContainer.scrollHeight;
                    }
                    var systemContainer = document.getElementById('system-body-container');
                    if (systemContainer) {
                        systemContainer.scrollTop = systemContainer.scrollHeight;
                    }
                });
            },
            cleanUnReadMessage(key) {
                const info = this.listExtraInfo[key];
                if (info === undefined) {
                    return;
                }
                info.unread = 0;
                this.listExtraInfo[key] = info;
                // 需要手动刷新
                this.$forceUpdate();
            },
            incrementUnReadMessage(key) {
                // 消息未读数+1
                const info = this.listExtraInfo[key];
                if (info === undefined) {
                    this.listExtraInfo[key] = {
                        unread: 1
                    }
                } else {
                    info.unread = info.unread + 1;
                    this.listExtraInfo[key] = info;
                }
                // 需要手动刷新
                this.$forceUpdate();
            },
            isSelectPersonTag(){
                return this.chatsContent.select === 'friend' || this.chatsContent.select === 'session';
            },
            testUpload(){

            },
            // --------------- EChatIMSDK 事件回调 --------------- //
            onConnected() {
                this.online = 1;
            },
            onDisConnected() {
                this.online = 0;
            },
            onUserInfo(userInfo) {
                this.userInfo = userInfo;
            },
            // 接受到普通消息
            onMessageReceive(message) {
                if (message.way === 'P2P' || message.way === 'P2R') {
                    this.incrementUnReadMessage(message.way === 'P2P' ? message.fromUser : message.toTarget); // 消息未读数+1
                    if (this.windowTab === 'chat') {
                        // 群: 不要显示自己发送的消息
                        if (message.fromUser === this.userInfo.auid) {
                            return;
                        }
                        // 收到'P2P', 但打开了其它窗口
                        if (message.way === 'P2P') {
                            if (!this.isSelectPersonTag() || this.chatsContent.selectId !== message.fromUser)
                                return;
                        }
                        // 收到'P2R', 但打开了其它窗口
                        if (message.way === 'P2R') {
                            if (this.isSelectPersonTag() || this.chatsContent.selectId !== parseInt(message.toTarget))
                                return;
                        }
                        // 加入刚刚收到的信息到聊天窗口
                        const msgReceive = {
                            avatar: message.toTargetAvatar,
                            body: message.body,
                            createTime: new Date().toLocaleString(),
                            fromUser: message.fromUser,
                            fromUserAvatar: message.fromUserAvatar,
                            fromUserName: message.fromUserName,
                            toMe: 1,
                            toTarget: message.toTarget,
                            toTargetAvatar: message.toTargetAvatar,
                            toTargetName: message.toTargetName,
                            type: message.type,
                            way: message.way,
                        };
                        this.chatsContent.chats.push(msgReceive);
                        this.scrollMessageContainerToBottom();
                    }
                }
            },
            // 接受事件消息
            onEventReceive(event) {
                console.log("onEventReceive:" + Beans.json(event));
                if(event.eventType === 'CLIENT_ONLINE'){
                    var jsonBody = Beans.bean(event.body);
                    app.sessionList.forEach(function (v) {
                        if(v.toTarget === jsonBody.auid){
                            v.online = jsonBody.online;
                        }
                    });
                    app.friendList.forEach(function (v) {
                        if(v.auid === jsonBody.auid){
                            v.online = jsonBody.online;
                        }
                    });
                    if(app.chatsContent.friendInfo.auid === jsonBody.auid){
                        app.chatsContent.friendInfo.online = jsonBody.online;
                    }
                    app.$forceUpdate();
                }
            },
            onSessionList(resp) {
                console.log(resp);
                // throw new Error("onSessionList");
                this.sessionList = resp;
                var targetAuids = this.sessionList.map(function (v) {
                    return v.toTarget;
                });
                // 监听最近会话的在线状态
                im.apis.addOnlineMonitor.call({auid:app.userInfo.auid, targetAuids:targetAuids}).then((resp) => {
                    // app.showToast("设置成功");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            onFriendList(resp) {
                console.log(resp);
                this.friendList = resp;

                var targetAuids = this.friendList.map(function (v) {
                    return v.auid;
                });
                // 监听朋友的在线状态
                im.apis.addOnlineMonitor.call({auid:app.userInfo.auid, targetAuids:targetAuids}).then((resp) => {
                    // app.showToast("设置成功");
                }).catch((e) => {
                    app.showApiErrorToast(e);
                })
            },
            onBlacklistForbidList(resp) {

            },
            onRoomList(resp) {
                console.log(resp);
                this.roomList = resp;
            },
            onError(e) {
                this.showApiErrorToast(e);
            },
        }
    });
    // 初始化 EChatIMSDK
    initEasyIMSDKWithConfig();

}

// EChatIMSDK 事件回调绑定
const EasyIMSDKListenerMap = {
    onConnected: () => {
        window.app.onConnected()
    },
    onDisConnected: () => {
        window.app.onDisConnected()
    },
    onUserInfo: (userInfo) => {
        window.app.onUserInfo(userInfo)
    },
    onMessageReceive: (resp) => {
        window.app.onMessageReceive(resp)
    },
    onEventReceive: (resp) => {
        window.app.onEventReceive(resp)
    },
    onSessionList: (resp) => {
        window.app.onSessionList(resp)
    },
    onFriendList: (resp) => {
        window.app.onFriendList(resp)
    },
    onBlacklistForbidList: (resp) => {
        window.app.onBlacklistForbidList(resp)
    },
    onRoomList: (resp) => {
        window.app.onRoomList(resp)
    },
    onError: (e) => {
        window.app.onError(e)
    }
};

function initEasyIMSDKWithConfig() {
    const app = window.app;

    const sdkConfig = {};
    // sdkConfig.host = 'localhost';
    // sdkConfig.httpPort = 8082;
    // sdkConfig.socketPort = 9092;
    // 为统一部署，更改发布版的host为demo.echat.work
    sdkConfig.host = 'demo.echat.work';
    sdkConfig.httpPort = 58082;
    sdkConfig.socketPort = 59092;
    sdkConfig.key = 'TSDKTEST00001';
    sdkConfig.secret = '';
    sdkConfig.apiTransport = 'HTTP';
    // sdkConfig.loginAuid = 'admin';
    sdkConfig.loginAuid = Cookies.get('userAuid');
    // sdkConfig.loginToken = 'admin';
    sdkConfig.loginToken = Cookies.get('userToken');
    sdkConfig.listeners = {};
    for (var v in EasyIMSDKListenerMap) {
        sdkConfig.listeners[v] = EasyIMSDKListenerMap[v];
    }
    sdkConfig.fileServerConfig = {
        // use: 'aliyun',
        use: 'local',
        client: 'plupload',
        baseUrl: 'http://localhost:8082',
        // baseUrl: 'http://api.echat.work:8082',
        version: 'v1',
    };

    // chatList.showModifyUserInfoModal();
    app.userInfo.auid = sdkConfig.loginAuid;
    initEasyIMSDK(sdkConfig);
}


function initEasyIMSDK(sdkConfig) {
    if (window.im === undefined) {
        console.error("Not found echatim sdk, please import echatim-sdk.js first.");
        return;
    }
    var im = window.im;
    im.init(sdkConfig, function (sdk) {
        if (sdk) {
            console.info('echatIMSDK 成功连接, 可以使用 EChatIMApis 请求数据了.');
        } else {
            throw Error("echatIMSDK 初始化失败");
        }
    });

}


function getUrlParam(param) {
    const query = window.location.search.substring(1);
    const vars = query.split("&");
    for (let i = 0; i < vars.length; i++) {
        const pair = vars[i].split("=");
        if (pair[0] === param) {
            return pair[1];
        }
    }
    return null;
}
